package com.fywsy.fyweb.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.*;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.util.LinkedMultiValueMap;

import java.util.List;
import java.util.Map;
import java.util.HashMap;


public class RestTemplateUtil {
    private static final RestTemplate restTemplate = new RestTemplate();

    /**
     * 发送POST请求，提交表单数据
     * @param url 请求的URL
     * @param formData 表单数据
     * @return 响应结果
     */
    public static String sendPostForm(String url, MultiValueMap<String, String> formData) {
        return sendPostFormAndGetJsonKey(url, formData, null);
    }

    public static String sendPostFormAndGetJsonKey(String url, MultiValueMap<String, String> formData,String jsonKey) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 创建请求实体
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(formData, headers);

        try {
            // 发送POST请求
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            if(TextUtils.isEmpty(jsonKey)) return response.getBody();
            try {
                // 解析响应
                JsonObject jsonResponse = JsonParser.parseString(response.getBody()).getAsJsonObject();
                return jsonResponse.get(jsonKey).getAsString();
            } catch (Exception e) {
                return "";
            }
        } catch (HttpClientErrorException e) {
            return "Error: " + e.getResponseBodyAsString();
        }
    }

    /**
     * 发送POST请求，提交JSON数据
     * 同时获取返回结果json内key的value
     * @param url 请求的URL
     * @param jsonData JSON数据
     * @return 响应结果
     */
    public static String sendPostJsonAndGetJsonKey(String url, String jsonData,String jsonKey,MultiValueMap<String,String> header) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        if(header != null && header.size() > 0) {
            headers.addAll(header);
        }

        // 创建请求实体
        HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);

        try {
            // 发送POST请求
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            try {
                // 解析响应
                JsonObject jsonResponse = JsonParser.parseString(response.getBody()).getAsJsonObject();
                return jsonResponse.get(jsonKey).getAsString();
            } catch (Exception e) {
                return "";
            }
        } catch (HttpClientErrorException e) {
            return "Error: " + e.getMessage();
        }
    }


    public static String sendPostJsonAndGetJsonKey(String url, Map map,String jsonKey) {
        return sendPostJsonAndGetJsonKey(url,new Gson().toJson(map),jsonKey,null);
    }

    public static String sendPostJsonAndGetJsonKey(String url, Map map,String jsonKey, MultiValueMap<String,String> header) {
        return sendPostJsonAndGetJsonKey(url,new Gson().toJson(map),jsonKey,header);
    }

    /**
     * 发送POST请求，提交JSON数据
     * @param url 请求的URL
     * @param jsonData JSON数据
     * @return 响应结果
     */
    public static String sendPostJson(String url, String jsonData) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 创建请求实体
        HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);

        try {
            // 发送POST请求
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            return response.getBody();
        } catch (HttpClientErrorException e) {
            return "Error: " + e.getResponseBodyAsString();
        }
    }


    public static String sendPostJson(String url, Map map) {
        return sendPostJson(url,new Gson().toJson(map));
    }

    /**
     * 发送POST请求，提交带有JSON体的请求
     * @param url 请求的URL
     * @param headers 请求头
     * @param jsonData JSON数据
     * @return 响应结果
     */
    public static String sendPostJsonWithHeaders(String url, HttpHeaders headers, String jsonData) {
        // 创建请求实体
        HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);

        try {
            // 发送POST请求
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            return response.getBody();
        } catch (HttpClientErrorException e) {
            return "Error: " + e.getResponseBodyAsString();
        }
    }


    /**
     * 发送GET请求
     * @param url 请求的URL
     * @return 响应结果
     */
    public static String sendGet(String url) {
        try {
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            return response.getBody();
        } catch (HttpClientErrorException e) {
            return "Error: " + e.getResponseBodyAsString();
        }
    }

    /**
     * 发送带请求头的GET请求
     * @param url 请求的URL
     * @param headers 请求头
     * @return 响应结果
     */
    public static String sendGetWithHeaders(String url, HttpHeaders headers) {
        try {
            HttpEntity<String> entity = new HttpEntity<>(headers);
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
            return response.getBody();
        } catch (HttpClientErrorException e) {
            return "Error: " + e.getResponseBodyAsString();
        }
    }

    /**
     * 发送GET请求并获取返回JSON中指定key的值
     * @param url 请求的URL
     * @param jsonKey 要获取的JSON key
     * @return 指定key的值
     */
    public static String sendGetAndGetJsonKey(String url, String jsonKey) {
        return sendGetAndGetJsonKey(url, jsonKey, null);
    }

    /**
     * 发送带请求头的GET请求并获取返回JSON中指定key的值
     * @param url 请求的URL
     * @param jsonKey 要获取的JSON key
     * @param headers 请求头
     * @return 指定key的值
     */
    public static String sendGetAndGetJsonKey(String url, String jsonKey, HttpHeaders headers) {
        try {
            HttpEntity<String> entity = headers != null ? new HttpEntity<>(headers) : null;
            ResponseEntity<String> response = entity != null ?
                    restTemplate.exchange(url, HttpMethod.GET, entity, String.class) :
                    restTemplate.getForEntity(url, String.class);

            JsonObject jsonResponse = JsonParser.parseString(response.getBody()).getAsJsonObject();
            return jsonResponse.get(jsonKey).getAsString();
        } catch (HttpClientErrorException e) {
            return "Error: " + e.getResponseBodyAsString();
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 发送POST请求，提交表单数据并获取响应头中的cookie
     * @param url 请求的URL
     * @param formData 表单数据
     * @return cookie字符串
     */
    public static String sendPostFormAndGetCookie(String url, MultiValueMap<String, String> formData) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 创建请求实体
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(formData, headers);

        try {
            // 发送POST请求
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            List<String> cookies = response.getHeaders().get("Set-Cookie");
            if (cookies != null && !cookies.isEmpty()) {
                StringBuilder cookieBuilder = new StringBuilder();
                for (String cookie : cookies) {
                    if (cookieBuilder.length() > 0) {
                        cookieBuilder.append("; ");
                    }
                    cookieBuilder.append(cookie.split(";")[0]);
                }
                return cookieBuilder.toString();
            }
            return "";
        } catch (HttpClientErrorException e) {
            return "Error: " + e.getResponseBodyAsString();
        }
    }

    /**
     * 发送POST请求，提交表单数据并使用cookie
     * @param url 请求的URL
     * @param formData 表单数据
     * @param jsonKey 要获取的JSON key
     * @param cookie cookie字符串
     * @return 指定key的值
     */
    public static String sendPostFormAndGetJsonKeyWithCookie(String url, MultiValueMap<String, String> formData, String jsonKey, String cookie) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.set("Cookie", cookie);

        // 创建请求实体
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(formData, headers);

        try {
            // 发送POST请求
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            if(TextUtils.isEmpty(jsonKey)) return response.getBody();
            try {
                // 解析响应
                JsonObject jsonResponse = JsonParser.parseString(response.getBody()).getAsJsonObject();
                return jsonResponse.get(jsonKey).getAsString();
            } catch (Exception e) {
                return "";
            }
        } catch (HttpClientErrorException e) {
            return "Error: " + e.getResponseBodyAsString();
        }
    }

    /**
     * 发送POST请求，提交表单数据并获取响应头
     * @param url 请求的URL
     * @param formData 表单数据
     * @return 响应头Map
     */
    public static Map<String, String> sendPostFormAndGetHeaders(String url, Map<String, String> formData) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.set("accept", "*/*");
        headers.set("accept-language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
        headers.set("x-requested-with", "XMLHttpRequest");

        // 创建请求实体
        MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();
        formData.forEach(multiValueMap::add);
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(multiValueMap, headers);

        try {
            // 发送POST请求
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            Map<String, String> responseHeaders = new HashMap<>();
            response.getHeaders().forEach((key, value) -> {
                if (!value.isEmpty()) {
                    responseHeaders.put(key, value.get(0));
                }
            });
            return responseHeaders;
        } catch (HttpClientErrorException e) {
            return null;
        }
    }

    /**
     * 发送POST请求，提交表单数据并获取JSON响应中的指定key
     * @param url 请求的URL
     * @param formData 表单数据
     * @param jsonKey 要获取的JSON key
     * @param headers 请求头
     * @return 指定key的值
     */
    public static String sendPostFormAndGetJsonKey(String url, MultiValueMap<String, String> formData, String jsonKey, MultiValueMap<String, String> headers) {
        // 设置请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        if (headers != null) {
            headers.forEach((key, value) -> {
                if (value != null && !value.isEmpty()) {
                    httpHeaders.add(key, value.get(0));
                }
            });
        }

        // 创建请求实体
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(formData, httpHeaders);

        try {
            // 发送POST请求
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            if (TextUtils.isEmpty(jsonKey)) return response.getBody();
            try {
                // 解析响应
                JsonObject jsonResponse = JsonParser.parseString(response.getBody()).getAsJsonObject();
                return jsonResponse.get(jsonKey).getAsString();
            } catch (Exception e) {
                return "";
            }
        } catch (HttpClientErrorException e) {
            return "Error: " + e.getResponseBodyAsString();
        }
    }
}
